package com.fs.uc.base.repo;

import com.fs.uc.base.domain.Org;
import com.fs.uc.base.domain.OrgType;
import com.fs.uc.base.exception.NotFoundException;
import com.fs.uc.base.exception.ParamException;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.quarkus.panache.common.Parameters;

import javax.enterprise.context.ApplicationScoped;
import java.util.List;

/**
 * @author 崔超
 * 2021/12/2
 */
@ApplicationScoped
public class OrgRepository implements PanacheRepository<Org> {

    static final String LOGIN_NAME_FIELD = "loginName";
    static final String PASSWORD_FIELD = "password";
    static final String NAME_FIELD = "name";
    static final String REMOTE_ID_FIELD = "remoteId";
    static final String TYPE_FIELD = "type";

    public Org getById(Long orgId) {
        Org org = findById(orgId);
        if (org == null) {
            throw new NotFoundException();
        }
        return org;
    }

    public void updateOrg(Org org) {
        if (org.id == null) {
            throw new ParamException();
        }
        Org origin = findById(org.id);
        if (org.name != null)
            origin.name = org.name;
        if (org.loginName != null)
            origin.loginName = org.loginName;
        if (org.password != null)
            origin.password = org.password;
        if (org.type != null)
            origin.type = org.type;
        persist(org);
    }

    public Org findByLoginNameAndPassword(String loginName, String password) {
        Parameters param = Parameters.with(LOGIN_NAME_FIELD, loginName).and(PASSWORD_FIELD, password);
        return find("loginName = :loginName and password = :password", param).firstResult();
    }

    public Org findByLoginName(String loginName) {
        return find(LOGIN_NAME_FIELD, loginName).firstResult();
    }


    public Org findByName(String name) {
        return find(NAME_FIELD, name).firstResult();
    }

    public Org findByRemoteId(Long remoteId){return find(REMOTE_ID_FIELD,remoteId).firstResult();}

    public List<Org> findByType(OrgType type) {
        return list(TYPE_FIELD, type);
    }



}
